package com.prb.chat;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

public class WechatServer {


    private String split = "#@#";

    private Selector selector = null;

    private Charset charset = Charset.forName("UTF-8");

    ServerSocketChannel serverSocketChannel;


    public static void main(String[] args) throws IOException {

        new WechatServer().start(8099);


    }

    private void start(Integer port) throws IOException {

        //多路复用器
        selector = Selector.open();

        //服务端channel
        serverSocketChannel = ServerSocketChannel.open();
        //服务端channel 绑定
        serverSocketChannel.bind(new InetSocketAddress(port));

        // 设置非阻塞
        serverSocketChannel.configureBlocking(false);
        //注册到多路复用器
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("server is start-----");
        while (true){
            //判断多路复用器上边是否有可读通道
            int select = selector.select();

            if (select == 0) continue;

            //获取可读通道集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator keyIterator = selectionKeys.iterator();
            while(keyIterator.hasNext()) {
                SelectionKey sk = (SelectionKey) keyIterator.next();
                keyIterator.remove();
                //处理通道数据
                handlerChannel(sk);
            }

        }


    }

    private void handlerChannel(SelectionKey selectionKey) throws IOException {

        //进行建立连接
        if (selectionKey.isAcceptable()) {

            SocketChannel channel = serverSocketChannel.accept();
            channel.configureBlocking(false);
            //绑定多路复用器
            channel.register(selector, SelectionKey.OP_READ);

            System.out.println("listener remote addr is :" + channel.getRemoteAddress());
            channel.write(charset.encode("input your name"));

        }
        // 处理客户端读请求操作
        else if (selectionKey.isReadable()) {
            SocketChannel channel = (SocketChannel) selectionKey.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            channel.read(buffer);

            sendMsg(channel , buffer);
        }


    }

    private void sendMsg(SocketChannel channel , ByteBuffer buffer) throws IOException {

        buffer.flip();
        StringBuilder content = new StringBuilder();
        content.append(charset.decode(buffer));

        String msg = content.toString();

        String[] split = msg.split(this.split);

        System.out.println("server receiving:");
        for (String s : split) {
            System.out.println(s);
        }

        if (split.length == 1) {
            channel.write(charset.encode("server response : " + split[0]));
            return;
        }

        for (SelectionKey key : selector.keys()) {

            if(key.channel() instanceof SocketChannel){

                ((SocketChannel) key.channel()).write(charset.encode(split[1]));
            }

        }


    }

}
